package com.jinyang.jetpackdemo.util;

import android.content.Context;
import android.os.Looper;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jinyang.jetpackdemo.R;

/**
 * Created by Mr.LJY on 2017/12/25.
 */
public class LjyToastUtil {

    private static Toast mToast;
    private Context context;

    private LjyToastUtil() {
    }

    private static class LjyToastUtilHolder {
        private static final LjyToastUtil INSTANCE = new LjyToastUtil();
    }

    public static LjyToastUtil getInstance() {
        return LjyToastUtilHolder.INSTANCE;
    }


    public void init(Context context) {
        this.context = context.getApplicationContext();
    }

    /**
     * 唯一的toast
     *
     * @param text
     */
    public void toast(CharSequence text) {
        if (TextUtils.isEmpty(text)) {
            return;
        }
        if (Looper.myLooper() == Looper.getMainLooper()) {
//        if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
//        if (Looper.getMainLooper().isCurrentThread()) {
            makeText(text);
        } else {
            Looper.prepare();
            makeText(text);
            Looper.loop();
        }
    }

    private void makeText(final CharSequence s) {
        if (context == null) {
            return;
        }
        if (mToast == null) {
            mToast = new Toast(context);
        }
        RelativeLayout contentRl = (RelativeLayout) View.inflate(context, R.layout.toast_common, null);
        ((TextView) contentRl.findViewById(R.id.tv_toast_common)).setText(s);
        mToast.setView(contentRl);
        mToast.setGravity(Gravity.BOTTOM, 0, 200);
        mToast.show();
    }

}